<?php

namespace app\admin2\controller;

use think\Session;
use app\common\controller\AdminBaseo;
use app\common\model\WxUser as WxUserModel;
use app\common\util\WechatThirdUtil;
use htq\HTQClient; //队列类


use think\Controller;
use app\common\model\Pushmessage as PushmessageModel;
use app\common\model\AuthorWxUser;
use app\common\model\Users as UsersModel;

class Template extends AdminBaseo
{
    protected $config;
    protected $wechat_obj;
    protected $third_config;
    protected $wx_user_model;
    protected $HTQClient;

    protected $author_wx_user;
    protected $pushmessage_model;
    protected $users_model;

    private $request_uri3;  // 请求node的接口

    protected function _initialize()
    {
        parent::_initialize();
        $this->wx_user_model = new WxUserModel();
        $this->config = Session::get('wechat_info'); //当前授权公众号信息
        $this->third_config = $this->wx_user_model->find(); //第三方开发平台信息
        $this->wechat_obj = new WechatThirdUtil($this->third_config, $this->config);
        $this->author_wx_user = new AuthorWxUser;
        $this->HTQClient = new HTQClient('J6E04AifABuDRfsMm2Qt4WMJHq201vmz', 'Hc9KVU6cGDWxoQ7PjSxwYQOLrCcg6wFj');

        $this->pushmessage_model = new PushmessageModel();
        $this->users_model = new UsersModel();

        $this->request_uri3 = NEW_NODE_URL;
    }

    /*
     * 新增模板消息测试接口
     * 获取可以发送的模板消息列表
     * */
    public function getTemplateList()
    {
//        1 获取模板列表
        $template_list = $this->wechat_obj->getTemplateList();
        // return $this->thinkJson($template_list);
        return json($template_list);
    }

    /*
     * 模板消息的发送
     * */
    public function sendTemplateMsg($data)
    {
        $json_result = base64_decode($data);
        $template_msg = json_decode($json_result, true);
        $send_openids = $template_msg['openid'];
        foreach ($send_openids as $openid) {
            file_put_contents('./abc.log', $openid, FILE_APPEND);
            $template_msg['data']['touser'] = $openid;
            $result = $this->wechat_obj->sendTemplateMsg($template_msg['data']);
            if (!$result) {
                //如果发生错误会提醒管理员 return只是暂时的
                return json(['status' => -1, 'error' => 'send template error']);
            }
        }
        //队列全部执行完并提醒管理员 return只是暂时的 删除队列
        $return = $this->HTQClient->deleteQueue($template_msg['queue_name']);
        if ($return['error_code'] == 1004) {
            //删除失败
            return false;
        }

        return json(['status' => 1, 'mag' => 'ok']);
    }

    public function queue()
    {
        $template_msg = $this->request->post();
        //队列名称
        $queue_name = 'queue_'.date('Ymd').'_'.session::get('admin_id').date('His').rand(1, 9999);
        $template_msg['queue_name'] = $queue_name;
        $url = QUEUE_URL.'/api/Template/sendTemplateMsg/auid/'.$this->config['id'];
        $ret = $this->HTQClient->addQueue($queue_name, 'real_time');
        if ($ret['error_code'] == 1002) {
            //队列已存在请重新操作
            return false;
        }
        $result = $this->HTQClient->addTask($queue_name, $url, $template_msg);
        if ($result['error_code'] == 0) {
            //队列任务添加成功
            return json(['status' => 1, 'msg' => 'ok']);
        } elseif ($result['error_code'] == 1001) {
            //队列任务添加失败
            return false;
        }
    }

    // 发送屏蔽广东省和武汉市的用户
    public function queueWG()
    {
        $template_msg = $this->request->post();
        //队列名称
        $queue_name = 'queue_'.date('Ymd').'_'.session::get('admin_id').date('His').rand(1, 9999);
        $template_msg['queue_name'] = $queue_name;
        $url = QUEUE_URL.'/newapi/Template/sendTemplateMsgWithoutWG/auid/'.$this->config['id'];
        $ret = $this->HTQClient->addQueue($queue_name, 'real_time');
        if ($ret['error_code'] == 1002) {
            //队列已存在请重新操作
            return false;
        }
        $result = $this->HTQClient->addTask($queue_name, $url, $template_msg);
        if ($result['error_code'] == 0) {
            //队列任务添加成功
            return json(['status' => 1, 'msg' => 'ok']);
        } elseif ($result['error_code'] == 1001) {
            //队列任务添加失败
            return false;
        }
    }
    // 只发给一个城市 默认是香港 中西区  尚凝小熊接口
    public function queueCity($city='')
    {
        if(empty($city)){
            $city = '中西区';
        }
        $template_msg = $this->request->post();
        //队列名称
        $queue_name = 'queue_'.date('Ymd').'_'.session::get('admin_id').date('His').rand(1, 9999);
        $template_msg['queue_name'] = $queue_name;
        $url = QUEUE_URL.'/newapi/Template/sendTemplateMsgCity/auid/'.$this->config['id'].'/city/'.$city;
        $ret = $this->HTQClient->addQueue($queue_name, 'real_time');
        if ($ret['error_code'] == 1002) {
            //队列已存在请重新操作
            return false;
        }
        $result = $this->HTQClient->addTask($queue_name, $url, $template_msg);
        if ($result['error_code'] == 0) {
            //队列任务添加成功
            return json(['status' => 1, 'msg' => 'ok']);
        } elseif ($result['error_code'] == 1001) {
            //队列任务添加失败
            return false;
        }
    }

    public function queueAll()
    {
        $ret = $this->HTQClient->allQueue();
        dump($ret);
    }

    public function getQueueAll()
    {
        $ret = $this->HTQClient->allQueue();

        return $ret;
    }

    public function del()
    {
        $queueall = $this->getQueueAll();
        foreach ($queueall as $v) {
            $ret = $this->HTQClient->deleteQueue($v['queue_name']);
            var_dump($ret);
        }
    }

    public function count()
    {
        $queueall = $this->getQueueAll();
        foreach ($queueall as $v) {
            $ret = $this->HTQClient->countQueue($v['queue_name']);
            var_dump($ret);
        }
    }

    public function actioning_queue($queue_name, $url)
    {
        $ret = $this->HTQClient->addTask($queue_name, $url);
        return $ret;
    }

    // ====================================================== 模板消息测试代码 ===================================== //

    // 启动模板消息
    public function startTemplate(){
        //  创建模板消息发送   /TemplaList/create
        $result =  $this->sendGet($this->request_uri3);
        return json($result);
    }
    // 向指定队列添加openid   /TemplaList/addopenid
    public function addOpenids(){
        $data = ['o5eJs0esozstbeHTlwNUXXyOkpE8',
            'o5eJs0SvHwzL7z3XOL5RHtFZVE4I',
            'o5eJs0ceePyPjhBJ-F9yD-ERAcmY',
            'o5eJs0T49hHqPrcjSCHvgTZdBrYs',
            'o5eJs0bS_ua371awfcd0pkP8mtLc',
            'o5eJs0RZl8tf-yCdpTLUA2KSAaaM', ];
        $result = $this->sendPost($this->request_uri3,$data);
        return json($result);
    }
    // 从指定队列中删除openid  get返回目前队列中的openid列表, post则删除对应的数据
    public function editOpenids(){

    }

    // 开始发送模板消息（开始发送不能取消  /TemplaList/start  tempData
    public function doTemplate(){
        $data = [];
        $str = '{
           "touser":"olDrH0tNRPEOlWXwx3lEzb-Tb_UM",
           "template_id":"iSSQFdqmxUDfnQ6dpX2sm9o47Xy2a_uDwxU_2eq1X2U",
           "url":"https://www.baidu.com/",
           "data":{
                   "first": {
                       "value":"恭喜你购买成功！",
                       "color":"#173177"
                   },
                   "activity_name":{
                       "value":"活动名称",
                       "color":"#173177"
                   },
                   "reserve_results": {
                       "value":"预约结果",
                       "color":"#173177"
                   },
                   "activity_time": {
                       "value":"活动时间",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买！",
                       "color":"#173177"
                   }
           }
       }';
        $data['data'] = json_decode($str, true);
        $result = $this->sendPost($this->request_uri3,$data['data']);
        return json($result);
    }

    // 请求模式get
    private function sendGet($url, $get_str=''){
        $result = httpRequest($url, 'GET', $get_str);
        if (!$result) {
            return false;
        }
        return $result;
    }
    // 请求模式post
    private function sendPost($url, $post_arr)
    {
        $result = httpRequest($url, 'POST', $post_arr);
        if (!$result) {
            return false;
        }

        return $result;
    }

    // 海草营销系统 auid = 111 直接一条发送模板消息给尚凝小安
    public function sendOneModel(){
        $data = [];
        $str = '{
           "touser":"olDrH0tNRPEOlWXwx3lEzb-Tb_UM",
           "template_id":"iSSQFdqmxUDfnQ6dpX2sm9o47Xy2a_uDwxU_2eq1X2U",
           "url":"https://www.baidu.com/",
           "data":{
                   "first": {
                       "value":"恭喜你购买成功！",
                       "color":"#173177"
                   },
                   "activity_name":{
                       "value":"活动名称",
                       "color":"#173177"
                   },
                   "reserve_results": {
                       "value":"预约结果",
                       "color":"#173177"
                   },
                   "activity_time": {
                       "value":"活动时间",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买！",
                       "color":"#173177"
                   }
           }
       }';
        $this->config = $this->author_wx_user->where('id', 111)->find();
        $this->wechat_obj = new WechatThirdUtil($this->third_config, $this->config);

        $data['data'] = json_decode($str, true);
        var_dump($data);

        $result = $this->wechat_obj->sendTemplateMsg($data['data']);
        var_dump($result);
    }

    public function test()
    {
        $data = [];
        $str = '{
            "template_id":"6wc9MhDK36MhgujGxjtJ1W9CP_i5SRgIvaB66l4tY4M",
            "url":"https://www.baidu.com",           
            "data":{
                    "first": {
                        "value":"恭喜，测试通过！",
                        "color":"#173177"
                    },
                    "keyword1":{
                        "value":"这是测试业务",
                        "color":"#173177"
                    },
                    "keyword2": {
                        "value":"2018-07-07 10:30",
                        "color":"#173177"
                    },
                    "remark":{
                        "value":"只是测试业务，不用理会，谢谢",
                        "color":"#173177"
                    }
            }
        }';

        $data['openid'] = ['o5eJs0esozstbeHTlwNUXXyOkpE8',
        'o5eJs0SvHwzL7z3XOL5RHtFZVE4I',
        'o5eJs0ceePyPjhBJ-F9yD-ERAcmY',
        'o5eJs0T49hHqPrcjSCHvgTZdBrYs',
        'o5eJs0bS_ua371awfcd0pkP8mtLc',
        'o5eJs0RZl8tf-yCdpTLUA2KSAaaM', ];
        $data['data'] = json_decode($str, true);

        return $data;
    }

    public function test2($data)
    {
        $json_result = base64_decode($data);
        $template_msg = json_decode($json_result, true);
        dump($template_msg);
    }
}
